<template>
  <div>
    <div>scroll-tap</div>
    <div>scroll-tap</div>
    <div>scroll-tap</div>
    <div>scroll-tap</div>
    <div>scroll-tap</div>
    <div>scroll-tap</div>
    <div>scroll-tap</div>
    <div>scroll-tap</div>
    <div>
      <div ref="btns" class="btnList" :class="{ 'btns-float' :isBtnsFloat }">
        <button v-for="(cel, index) in h2List" :key="'h2'+index" @click="goH2(index)">{{cel.innerText}}</button>
      </div>
      <div class="btnsBrother" v-show="isBtnsFloat"></div>
      <div ref="container" v-html="HTML_DATA"></div>
    </div>
  </div>
</template>

<script>
    import { HTML_DATA } from './data.js'
    export default {
      data () {
        return {
          HTML_DATA: '',
          h2List: [],
          isBtnsFloat: false,
          myTimer: null
        }
      },
      mounted () {
        this.HTML_DATA = HTML_DATA
        setTimeout(() => {
          this.h2List = this.$refs.container.getElementsByTagName('h2')
        }, 0)
        const btnsOffsetTop = this.$refs.btns.offsetTop
        window.addEventListener('scroll', () => {
          this.isBtnsFloat = document.documentElement.scrollTop >= btnsOffsetTop
        })
      },
      methods: {
        goH2 (index) {
          var preSpeed = 0
          clearInterval(this.myTimer)
          const btnListHeight = 50
          const targetValue = this.h2List[index].offsetTop - btnListHeight

          this.myTimer = setInterval(() => {
            var activeTop = window.scrollY
            var speed = (targetValue - activeTop) / 5
            // if (speed < 1 && speed > -1) { 最后一个tab内容太少会有bug
            if (preSpeed === speed) {
              // ie 中 对象 不支持 scrollTo(0, x), 可以用scrollTop = x
              window.scrollTo(0, targetValue)
              clearInterval(this.myTimer)
            } else {
              window.scrollTo(0, activeTop + speed)
              preSpeed = speed
            }
          }, 10)
        }
      }
    }
</script>

<style>
  .btns-float{
    position: fixed;
    top: 0px;
  }
  .btnList{
    width: 100%;
    background:white;
    height: 50px;
    border: 1px solid black;
  }
  .btnsBrother{
    width: 10px;
    height: 50px;
  }
</style>